<template>
  <teleport to="body">
    <div v-if="modelValue" class="modal-overlay" @click="close">
      <div class="modal-content" @click.stop>
        <header class="modal-header">
          <h3>{{ title }}</h3>
          <label @click="onCancel" style="cursor: pointer;">
            x
          </label>
        </header>
        <main class="modal-body">
          <slot></slot>
        </main>
        <footer class="modal-footer" v-if="footerShow">
          <MButton @click="submit" style="height: 25px;width: 80px;">确定</MButton>
          <MButton @click="onCancel" style="height: 25px;width: 80px;">取消</MButton>
        </footer>
      </div>
    </div>
  </teleport>
</template>

<script>
import { defineComponent } from 'vue';
import closeIcon from '@/resource/close.png'
import MButton from './MButton.vue';

export default defineComponent({
  name: 'MModal',
  components: {
    MButton
  },
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: 'Modal Title'
    },
    onSubmit: {
      type: Function,
      default: null
    },
    onCancel: {
      type: Function,
      default: null
    },
    footerShow: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue', 'submit'],
  setup(props, { emit }) {
    const close = () => {
      emit('update:modelValue', false);
    };

    const submit = () => {
      if (props.onSubmit) {
        props.onSubmit();
      } else {
        emit('submit');
      }
    };

    return { close, submit, closeIcon };
  }
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 230px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 20px 0;
}

.modal-footer {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px 0;
}

button {
  cursor: pointer;
}
</style>
